package top.bfylu.command.undo;

/**
 * 包名: top.bfylu.command.undo
 * 创建时间: 2022/2/7
 *
 * @author bfy
 * @version 1.0.0
 * <p>
 * 描述:
 * @Email bfyjian@gmail.com
 **/
public class RemoteControlWithUndo {
    Command[] onCommands;
    Command[] offCommands;
    Command undoCommand; //前一个命令将被记录在这里

    //创建构造方法，并初始化参数
    public RemoteControlWithUndo() {
        onCommands = new Command[7];
        offCommands = new Command[7];

        Command noCommand = new NoCommand();
        for (int i=0; i<7; i++) {
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
        //一开始，并没有所谓的“前一个命令”，所以将它设置成noCommand的对象
        undoCommand = noCommand;
    }

    public void setCommand(int slot, Command onCommand, Command offCommand) {
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }

    /**
     * 当按下按钮，我们取得这个命令并优先执行它，然后将它记录在undoCommand实例变
     * 量中。不管是“开“或”关“命令，我们的处理方法都一样的。
     * @param slot
     */
    public void onButtonWasPushed(int slot) {
        onCommands[slot].execute();
        undoCommand = onCommands[slot];
    }

    public void offButtonWasPushed(int slot) {
        offCommands[slot].execute();
        undoCommand = offCommands[slot];
    }

    /**
     * 当按下撤销按钮，我们调用undoCommand实例变量的undo()方法，就可以倒转前一个命令
     */
    public void undoButtonWasPushed() {
        undoCommand.undo();
    }

    //这里是toString代码
    public String toString() {
        StringBuffer stringBuff = new StringBuffer();
        stringBuff.append("\n------ Remote Control -------\n");
        for (int i = 0; i < onCommands.length; i++) {
            stringBuff.append("[slot " + i + "] " + onCommands[i].getClass().getName()
                    + "    " + offCommands[i].getClass().getName() + "\n");
        }
        stringBuff.append("[undo] " + undoCommand.getClass().getName() + "\n");
        return stringBuff.toString();
    }

}
